
#include "board.h"

const uint32_t OscRateIn = BOARD_CRYSTAL_FREQUENCY;
const uint32_t RTCOscRateIn	= BOARD_RTC_FREQUENCY;

static void System_Clock_IRC_64MHz(void)
{
    if(Chip_Clock_IsMainPLLConnected()) {
        Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL,SYSCTL_PLL_CONNECT);
    }

    if(Chip_Clock_IsMainPLLEnabled()) {
        Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL,SYSCTL_PLL_ENABLE);
    }

    Chip_Clock_SetCPUClockDiv(0);
    Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_IRC);
    Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL,31,1);
    Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL,SYSCTL_PLL_ENABLE);

    Chip_Clock_SetCPUClockDiv(1);
    while (!Chip_Clock_IsMainPLLLocked()) {}

    Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL,SYSCTL_PLL_CONNECT);

}

static void System_Clock_MAINOSC_Config(
    uint32_t pll_msel,
    uint32_t pll_nsel,
    uint32_t cpu_clk_div)
{
    /* Disconnect the Main PLL if it is connected already */
    if (Chip_Clock_IsMainPLLConnected()) {
        Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT);
    }

    /* Disable the PLL if it is enabled */
    if (Chip_Clock_IsMainPLLEnabled()) {
        Chip_Clock_DisablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE);
    }

    /* Enable the crystal */
    if (!Chip_Clock_IsCrystalEnabled()) {
        Chip_Clock_EnableCrystal();
    }

    int i=0;
    while(!Chip_Clock_IsCrystalEnabled()) {
        i++;
        if(i>0xFFFF) break;
    }

    Chip_Clock_SetCPUClockDiv(0);
    if(i>0xFFFF) {
        System_Clock_IRC_64MHz();
    } else {
        Chip_Clock_SetMainPLLSource(SYSCTL_PLLCLKSRC_MAINOSC);

        Chip_Clock_SetupPLL(SYSCTL_MAIN_PLL, pll_msel, pll_nsel);
        Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_ENABLE);

        Chip_Clock_SetCPUClockDiv(cpu_clk_div);
        while (!Chip_Clock_IsMainPLLLocked()) {} /* Wait for the PLL to Lock */
        Chip_Clock_EnablePLL(SYSCTL_MAIN_PLL, SYSCTL_PLL_CONNECT);
    }
}

void Board_SystemInit(void)
{

    Chip_Clock_SetCrystalRangeLo();
    System_Clock_MAINOSC_Config(USER_CFG_MAINOSCPLL_MSEL,USER_CFG_MAINOSCPLL_NSEL,USER_CFG_MAINOSCCPU_DIV);
    SystemCoreClockUpdate();
	
}
